<template>
  <div class="brands-page">
    <div class="container py-5">
      <!-- 品牌筛选 -->
      <div class="brand-filters mb-4">
        <div class="row align-items-center">
          <div class="col-md-6">
            <div class="search-box">
              <div class="input-group">
                <input
                  type="text"
                  class="form-control"
                  placeholder="搜索品牌..."
                  v-model="searchKeyword"
                >
                <button class="btn btn-outline-primary" type="button">
                  <i class="fas fa-search"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 字母索引 -->
      <div class="letter-index mb-4">
        <div class="letter-nav">
          <button
            class="letter-btn"
            :class="{ active: activeLetter === letter }"
            v-for="letter in letters"
            :key="letter"
            @click="setLetter(letter)"
          >
            {{ letter }}
          </button>
        </div>
      </div>

      <!-- 品牌网格 -->
      <div class="brands-grid">
        <!-- 加载状态 -->
        <div v-if="loading && brands.length === 0" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2 text-muted">正在加载品牌数据...</p>
        </div>
        
        <!-- 品牌列表 -->
        <div class="row" v-else-if="filteredBrands.length > 0">
          <div
            class="col-6 col-md-4 col-lg-3 col-xl-2 mb-4"
            v-for="brand in filteredBrands"
            :key="brand.id"
          >
            <div class="brand-card">
              <div class="brand-logo-wrapper">
                <img 
                  :src="brand.logoUrl" 
                  :alt="brand.name" 
                  class="brand-logo"
                  @error="(event) => { if (event.target) (event.target as HTMLImageElement).src = placeholderImage(120, 80) }"
                />
                <div class="brand-overlay">
                  <router-link :to="`/products?brandId=${brand.id}`" class="btn btn-primary btn-sm">
                    进入品牌
                  </router-link>
                </div>

              </div>
              <div class="brand-info">
                <h6 class="brand-name">{{ brand.name }}</h6>
                <p class="brand-desc">{{ brand.description || '暂无描述' }}</p>
                <div class="brand-stats">
                  <span class="product-count">{{ brand.productCount }}款商品</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 无数据提示 -->
        <div v-else class="text-center py-5">
          <i class="fas fa-store-slash fa-3x text-muted mb-3"></i>
          <p class="text-muted">{{ searchKeyword ? '未找到相关品牌' : '暂无品牌数据' }}</p>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="text-center mt-5" v-if="hasMore">
        <button class="btn btn-outline-primary" @click="loadMore" :disabled="loading">
          <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
          {{ loading ? '加载中...' : '加载更多' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'

// 导入真实的API
import { getBrandList } from '@/api/brand'
import { getBrandProductCount } from '@/api/product'
import type { Brand } from '@/types/brand'
import { Message } from '@/utils/message'

// 扩展的品牌类型，包含页面显示需要的额外字段
interface ExtendedBrand extends Brand {
  productCount: number
  letter: string
}

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 状态
const loading = ref(false)
const hasMore = ref(true)

const activeLetter = ref('全部')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 字母索引
const letters = ['全部', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

// 品牌数据
const brands = ref<ExtendedBrand[]>([])
const totalBrands = ref(0)

// 获取品牌首字母
const getBrandInitial = (name: string): string => {
  // 简单的首字母获取逻辑，可以根据需要改进
  const firstChar = name.charAt(0).toUpperCase()
  return /[A-Z]/.test(firstChar) ? firstChar : '其他'
}

// 获取品牌列表
const fetchBrands = async (append = false) => {
  if (!append) {
    loading.value = true
  }
  
  try {
    const queryParams: any = {
      page: append ? currentPage.value : 1,
      size: pageSize.value,
      status: 1 // 只获取启用的品牌
    }
    
    // 添加搜索关键词
    if (searchKeyword.value) {
      queryParams.keyword = searchKeyword.value
    }
    
    const response = await getBrandList(queryParams)
    
    const brandList: ExtendedBrand[] = response.data.records.map(brand => ({
      ...brand,
      // 添加缺失的字段
      logoUrl: brand.logoUrl || placeholderImage(120, 80),
      productCount: 0, // 初始值，稍后会异步获取
      letter: getBrandInitial(brand.name)
    }))
    
    // 异步获取每个品牌的商品数量
    await loadBrandProductCounts(brandList)
    
    if (append) {
      brands.value = [...brands.value, ...brandList]
    } else {
      brands.value = brandList
      currentPage.value = 1
    }
    
    totalBrands.value = response.data.total
    hasMore.value = brands.value.length < totalBrands.value
    
  } catch (error) {
    console.error('获取品牌列表失败:', error)
    Message.error('获取品牌列表失败')
  } finally {
    loading.value = false
  }
}

// 加载品牌商品数量
const loadBrandProductCounts = async (brandList: ExtendedBrand[]) => {
  try {
    // 并发获取所有品牌的商品数量
    const countPromises = brandList.map(async (brand) => {
      try {
        const count = await getBrandProductCount(brand.id)
        brand.productCount = count
      } catch (error) {
        console.error(`获取品牌 ${brand.name} 商品数量失败:`, error)
        brand.productCount = 0
      }
    })
    
    await Promise.all(countPromises)
  } catch (error) {
    console.error('批量获取品牌商品数量失败:', error)
  }
}

// 计算属性
const filteredBrands = computed(() => {
  let filtered = brands.value



  // 按字母过滤
  if (activeLetter.value !== '全部') {
    filtered = filtered.filter(brand => brand.letter === activeLetter.value)
  }

  // 按搜索关键词过滤（前端过滤，后端已经过滤过了）
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(brand =>
      brand.name.toLowerCase().includes(keyword) ||
      (brand.description && brand.description.toLowerCase().includes(keyword))
    )
  }

  return filtered
})

// 方法
const setLetter = (letter: string) => {
  activeLetter.value = letter
}



const loadMore = async () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value += 1
  await fetchBrands(true)
}

// 搜索功能
watch(searchKeyword, () => {
  // 重新获取品牌列表
  fetchBrands()
})

// 初始化
onMounted(() => {
  fetchBrands()
})
</script>

<style scoped>


/* 筛选器 */
.filter-tabs {
  display: flex;
  gap: 10px;
}

.filter-btn {
  padding: 8px 20px;
  border: 1px solid #dee2e6;
  background: white;
  color: #666;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.filter-btn:hover,
.filter-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

/* 字母索引 */
.letter-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.letter-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #dee2e6;
  background: white;
  color: #666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.letter-btn:hover,
.letter-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

/* 品牌卡片 */
.brand-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  height: 100%;
}

.brand-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
}

.brand-logo-wrapper {
  position: relative;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  overflow: hidden;
}

.brand-logo {
  max-width: 100px;
  max-height: 80px;
  object-fit: contain;
  filter: grayscale(100%);
  transition: filter 0.3s ease;
}

.brand-card:hover .brand-logo {
  filter: grayscale(0%);
}

.brand-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 123, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.brand-card:hover .brand-overlay {
  opacity: 1;
}

.brand-info {
  padding: 15px;
}

.brand-name {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 5px;
  color: #333;
}

.brand-desc {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
  line-height: 1.4;
}

.brand-stats {
  font-size: 12px;
  color: #999;
}

.product-count {
  background: #f8f9fa;
  padding: 2px 8px;
  border-radius: 10px;
}



/* 响应式优化 */
@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }

  .filter-tabs {
    justify-content: center;
    margin-bottom: 20px;
  }

  .letter-nav {
    gap: 3px;
  }

  .letter-btn {
    width: 35px;
    height: 35px;
    font-size: 12px;
  }

  .brand-logo-wrapper {
    height: 100px;
  }

  .brand-logo {
    max-width: 80px;
    max-height: 60px;
  }

  .brand-info {
    padding: 12px;
  }
}

@media (max-width: 576px) {
  .brands-grid .col-6 {
    flex: 0 0 50%;
    max-width: 50%;
  }


}
</style> 